/**
 * 部署 pay-gateway 
 */

const shell = require('shelljs');// 引入shell.js等依赖
const func = require('./../util/func.js');


/**
 * pay-gateway 
 * 
 * @param {*} src_path 下载源代码之后存放源代码的目录
 * @param {*} git_address 源代码地址
 * @param {*} deploy_dir 页面build之后，静态页面部署的目标
 */
async function pay_gateway(src_path, git_address, deploy_dir) {
    const project_name = func.gitProjectName(git_address);
    const project_dir = src_path + "/" + project_name;//项目路径

    func.deleteDir(project_dir);//如果旧代码存在，则删除

    //第一步，摘取代码
    const clone_code = await func.git_clone(src_path, git_address);
    if (clone_code != 0) {
        console.log('拉取pay-gateway代码失败 ');
        shell.echo('克隆pay-gateway失败，请检查克隆地址是否存在');
        shell.exit(1);
    }

    //第二步，复制到部署目录
    if (shell.test('-e', deploy_dir)) {//是否存在旧部署目录
        const node_module = deploy_dir + "/node_modules";
        const temp_dir = src_path + "/gateway_node_modules";
        if (shell.test('-e', node_module)) {
            shell.cp(node_module, temp_dir);//把node_modules目录，移到暂存目录
        }
        shell.rm('-rf', deploy_dir + "/*");//
        shell.rm('-rf', deploy_dir + "/.*");
        if (shell.test("-e", temp_dir)) {
            shell.cp(temp_dir, node_module);//把node_modules目录，移到暂存目录
            shell.rm("-rf", temp_dir);
        }
    } else {
        shell.mkdir("-p", deploy_dir);
    }
    shell.rm("-rf", project_dir + "/.git")//把.git删除掉
    shell.cp("-rf", project_dir + "/*", deploy_dir);//源代码复制到部署目标,包含隐藏文件
    shell.cp("-rf", project_dir + "/.*", deploy_dir);


    const code = func.bulid_npm(deploy_dir, "npm install");//运行 npm install
    const message = "构建pay-gateway" + (code == 0 ? "成功" : "失败");
    // code == 0 ? console.log(message) : console.error(message);
    shell.echo(message);

}

module.exports = {
    pay_gateway
}


//测试 pay_admin_web
function test() {
    // sudo rm -rf /deploy/src/pay-gateway 
    const src_path = '/deploy/src';
    const git_address = 'https://fanruifeng:taijun432@git.visioners.cn/charge/pay-gateway.git';
    const deploy_dir = '/deploy/pay_gateway';
    pay_gateway(src_path, git_address, deploy_dir);
}

// test();